package com.qf.cx.simplenms.reader.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.qf.cx.simplenms.link.api.LinkManager;
import com.qf.cx.simplenms.reader.api.Reader;
import com.qf.cx.simplenms.reader.api.ReaderManager;
import com.qf.cx.simplenms.reader.model.ReaderModel;
import com.qf.cx.simplenms.reader.spi.ReaderSpi;

@Service
@PropertySource("classpath:reader.properties")
public class ReaderManagerImpl implements ReaderManager {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	// name -> reader
	private final Map<String, ReaderSpi> map = new HashMap<>();
	@Autowired
	private LinkManager linkManager;
	@Autowired
	private Environment env;

	@PostConstruct
	public void init() {
		int port = Integer.parseInt(env.getProperty("port"));
		boolean success = linkManager.startListen(port);
		if (success) {
			logger.info("Start listening on {}", port);
		} else {
			logger.error("Failed start listening on {}", port);
		}
	}

	@Override
	public synchronized Reader getReader(String name) {
		Reader reader = map.get(name);
		if (reader == null) {
			logger.warn("no reader named '{}'", name);
		}
		return reader;
	}

	@Override
	public synchronized void updateCache(List<ReaderModel> list) {
		for (Iterator<Entry<String, ReaderSpi>> it = map.entrySet().iterator(); it.hasNext();) {
			Entry<String, ReaderSpi> e = it.next();

			boolean delete = true;
			for (ReaderModel readerModel : list) {
				if (readerModel.getName().equals(e.getKey())) {
					delete = false;
					break;
				}
			}
			if (delete) {
				ReaderSpi reader = e.getValue();
				reader.forceStop();
				it.remove();
				logger.debug("reader '{}' deleted", e.getKey());
			}
		}

		for (ReaderModel t : list) {
			ReaderSpi reader = map.get(t.getName());
			if (reader == null) {
				reader = new SequentialTagMemoryReader(t, linkManager, TagMemoryOrders.BANK_ASCENDING_ORDER);
				map.put(t.getName(), reader);
				logger.debug("add reader " + t.getName());
			} else {
				logger.debug("reader '{}' updating", t.getName());
				reader.updateReaderModel(t);
				logger.debug("reader '{}' updated", t.getName());
			}
		}
	}

	@Override
	public synchronized String dump() {
		StringBuilder sb = new StringBuilder();
		sb.append("<h1>readers</h1></br>");
		for (Entry<String, ReaderSpi> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("</br>").append(entry.getValue().dump()).append("</br>");
		}
		sb.append("</br>");
		return sb.toString();
	}

}
